import axios from 'axios';
import store from '@/store';
import router from '@/router';
import { removeToken, getToken } from '@/utils/auth';

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  withCredentials: true,
  timeout: 500000,
});
service.interceptors.request.use(config => {
  const token = getToken();
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
}, error => {
  console.error('Request error:', error);
  return Promise.reject(error);
});
service.interceptors.response.use(response => response, error => {
  const { response } = error; // Destructure for clarity

  if (response) {
    // Handle known error codes or messages
    switch (response.status) {
      case 401:
        console.log('未登录，将跳转至登录页面');
        removeToken();
        router.replace('/login');
        break;

      default:
        const errorMessage = handleErrorMessage(response.statusText);
        console.error(errorMessage);
        break;
    }
  } else {
    console.error('网络连接异常，请检查网络设置');
  }

  return Promise.reject(error);
});
function handleErrorMessage(message) {
  if (message === "Network Error") {
    return "后端接口连接异常";
  } else if (message.includes("timeout")) {
    return "系统接口请求超时";
  } else if (message.startsWith("Request failed with status code")) {
    return `系统接口${message.slice(-3)}异常`;
  }
  return message;
}

export default service;
